package wox.lonice.btctrade.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import wox.lonice.btctrade.common.BaseConstant;
import wox.lonice.btctrade.exception.TradeException;
import wox.lonice.btctrade.service.TradeService;
import wox.lonice.utis.HttpsUtils;
import wox.lonice.utis.MD5Util;
import wox.lonice.utis.ObjectUtil;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>描述：实现方法</p>
 *
 * @author LoNice
 * @Date 2018/5/28 10:18
 */
@Service
public class TradeServiceImpl implements TradeService, BaseConstant {
    private Logger logger = LoggerFactory.getLogger(TradeService.class);

    /**
     * 获取当前最新行情
     * Path：/api/v1/ticker/region/{btc|usc}

     Request类型：GET

     参数

     coin - eth

     region - 交易区：可选，btc、usc, 默认btc

     返回JSON dictionary

     high - 最高价

     low - 最低价

     buy - 买一价

     sell - 卖一价

     last - 最近一次成交价

     vol - 成交量

     返回结果示例

     {
     "code" : 0,
     "msg" : "Suceess",
     "result": true,
     "data":[
     "high":22,
     "low":20,
     "buy":1.879,
     "sell":0,
     "last":38800,
     "vol":283.954
     ]
     }
     * @throws Exception
     */
    @Override
    public JSONObject ticker(String domain, String area, String coin) throws TradeException {
        try {
            String httpUrl = domain + TICKER + area;

            String parms = "coin=" + coin;
            //请求数据
            String result = HttpsUtils.net(httpUrl, parms, HttpsUtils.METHOD_GET);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if("Suceess".equals(jsonObject.getString("msg"))){
                JSONObject jsonData = jsonObject.getJSONObject("data");
                if(ObjectUtil.isNotEmpty(jsonData)){
                    //最高价
                    BigDecimal hight = jsonData.getBigDecimal("high");
                    //最近一次成交价
                    BigDecimal last = jsonData.getBigDecimal("last");
                    //最低价
                    BigDecimal low = jsonData.getBigDecimal("low");
                    //买一价
                    BigDecimal buy = jsonData.getBigDecimal("buy");
                    //卖一价
                    BigDecimal sell = jsonData.getBigDecimal("sell");
                    //成交量
                    String vol = jsonData.getString("vol");
//                    System.out.println(jsonData);
                }
            }
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

    /**
     * 市场深度
     * Path：/api/v1/depth/region/{btc|usc}

     Request类型：GET

     参数

     region - 交易区：可选，btc、usc, 默认btc

     coin - coin

     返回JSON dictionary

     asks - 委买单[价格, 委单量]，价格从高到低排序

     bids - 委卖单[价格, 委单量]，价格从高到低排序

     返回结果示例：

     {
     "code" : 0,
     "msg" : "Suceess",
     "result": true,
     "asks": [
     [70000, 5],
     [69000, 0.48],
     [67000, 0.9999],
     [64498, 0.02]
     ...
     ],
     "bids": [
     [38300, 1.879],
     [38100, 1.0078],
     [38000, 1.24],
     [37700, 4.706]
     ...
     ]
     }
     * @throws Exception
     */
    @Override
    public JSONObject depth(String domain, String area, String coin) throws TradeException {
        try {
            String httpUrl = domain + DEPTH + area;
            String parms = "coin=" + coin;
            //请求数据
            String result = HttpsUtils.net(httpUrl, parms, HttpsUtils.METHOD_GET);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if("Suceess".equals(jsonObject.getString("msg"))){
                JSONObject jsonData = jsonObject.getJSONObject("data");
                if(ObjectUtil.isNotEmpty(jsonData)){
                    System.out.println(jsonData);
                }
            }
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

    /**
     * 十档与涨跌幅
     * @throws Exception
     */
    @Override
    public JSONObject order(String domain, String area, String coin) throws TradeException {
        try {
            String httpUrl = domain + "/coin/" + area + "/" + coin + "/order";

            //请求数据
            String result = HttpsUtils.net(httpUrl, null, HttpsUtils.METHOD_GET);
            JSONObject jsonObject = JSONObject.parseObject(result);
//            System.out.println(jsonObject);
            if(ObjectUtil.isNotEmpty(jsonObject.getString("f"))){
//                System.out.println(jsonObject.getString("f"));
            }
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

    /**
     * 账户信息
     * Path：/api/v1/balance/

     Request类型：POST

     参数

     key - API key

     signature - signature

     nonce - nonce

     返回JSON dictionary

     eth_balance - ETH总余额

     btc_balance - 比特币总余额

     eth_lock - ETH冻结余额

     btc_lock - 比特币冻结余额

     返回结果示例：

     {
     "code" : 0,
     "msg" : "Suceess",
     "result": true,
     "data": {
     "uid": "1",
     "xas_balance": 1,
     "xas_lock": 0,
     "eth_balance": 1,
     "eth_lock": 0,
     "btc_balance": 1,
     "btc_lock": 0
     }
     }
     * @throws Exception
     */
    @Override
    public JSONObject accountBalance(String domain) throws TradeException {
        try {
            String httpUrl = domain + ACCOUNT_BALANCE;
            String nonce = String.valueOf(new Date().getTime()).substring(0, 12);
            String signature = MD5Util.getMessageDigest(BTCTRADE_PRIVATE_KEY);
            String paramsValue = "key=" + BTCTRADE_PUBLIC_KEY + "&nonce=" + nonce;
            String parms = paramsValue + "&signature=" + MD5Util.sha256_HMAC(paramsValue, signature);
            //请求数据
            String result = HttpsUtils.net(httpUrl, parms, HttpsUtils.METHOD_POST);

            System.out.println(result);
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

    /**
     * 挂单查询
     * Path：/api/v1/trust_list/region/{btc|usc}

     Request类型：POST

     参数

     key - API key

     signature - signature

     nonce - nonce

     since - unix timestamp(utc timezone) default == 0, i.e. 返回所有

     coin - coin

     region - 交易区：可选，btc、usc, 默认btc

     type - 挂单类型[open:正在挂单, all:所有挂单]

     返回JSON dictionary

     id - 挂单ID

     coin - eth

     datetime - 时间戳

     type - "buy" or "sell"

     price - price

     status - 状态：1 （ 新挂单 ） 2 （ 开放交易 ）, 3 （ 撤销 ）, 4 （ 完全成交 ）

     amount_total - 委托数量

     amount_remain - 未成交数量

     返回结果示例：

     {
     "code" : 0,
     "msg" : "Suceess"
     "data": [{
     "id": "28",
     "datetime": "1508737051",
     "type": "sell",
     "price": 0.000123,
     "amount_total": 1213,
     "amount_remain": 1213
     }]
     }
     * @throws Exception
     */
    @Override
    public JSONObject trustList(String domain, String area, String coin) throws TradeException {
        try {
            String httpUrl = domain + TRUST_LIST + area;
            String nonce = String.valueOf(new Date().getTime()).substring(0, 12);
            String signature = MD5Util.getMessageDigest(BTCTRADE_PRIVATE_KEY);
            String paramsValue = "key=" + BTCTRADE_PUBLIC_KEY + "&nonce=" + nonce + "&coin=" + coin;
            String parms = paramsValue + "&signature=" + MD5Util.sha256_HMAC(paramsValue, signature);
            //请求数据
            String result = HttpsUtils.net(httpUrl, parms, HttpsUtils.METHOD_POST);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if("Suceess".equals(jsonObject.getString("msg"))){
                JSONArray jsonData = jsonObject.getJSONArray("data");
                if(ObjectUtil.isNotEmpty(jsonData)){
                    System.out.println(jsonData);
                }
            }
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

    /**
     * 查询订单信息
     * Path：/api/v1/trust_view/region/{btc|usc}

     Request类型：POST

     参数

     key - API key

     signature - signature

     nonce - nonce

     id - 挂单ID

     coin - coin

     region - 交易区：可选，btc、usc, 默认btc

     返回JSON dictionary

     id - 挂单ID

     datetime - 挂单时间（格式：时间戳）

     type - "buy" or "sell"

     price - 挂单价

     num_total - 委托数量

     num_over - 未成交数量

     status - 状态：1 （ 新挂单 ） 2 （ 开放交易 ）, 3 （ 撤销 ）, 4 （ 完全成交 ）

     返回结果示例：

     {
     "code": 0,
     "msg": "Suceess",
     "data": {
     "id": 28,
     "datetime": "1508737051",
     "type": "sell",
     "price": 0.000123,
     "num_total": 1213,
     "num_over": 1213,
     "status": "4"
     }
     }
     * @throws Exception
     */
    @Override
    public JSONObject trustView(String domain, String area, String coin, String id) throws TradeException {
        try {
            String httpUrl = domain + TRUST_VIEW + area;
            String nonce = String.valueOf(new Date().getTime()).substring(0, 12);
            String signature = MD5Util.getMessageDigest(BTCTRADE_PRIVATE_KEY);
            String paramsValue = "key=" + BTCTRADE_PUBLIC_KEY + "&nonce=" + nonce + "&id=" + id + "&coin=" + coin;
            String parms = paramsValue + "&signature=" + MD5Util.sha256_HMAC(paramsValue, signature);
            //请求数据
            String result = HttpsUtils.net(httpUrl, parms, HttpsUtils.METHOD_POST);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if("Suceess".equals(jsonObject.getString("msg"))){
                JSONArray jsonData = jsonObject.getJSONArray("data");
                if(ObjectUtil.isNotEmpty(jsonData)){
                    System.out.println(jsonData);
                }
            }
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

    /**
     * 取消订单
     * Trust_cancel（取消订单）

     Path：/api/v1/trust_cancel/region/{btc|usc}

     Request类型：POST

     参数

     key - API key

     signature - signature

     nonce - nonce

     id - 挂单ID

     coin - coin

     region - 交易区：可选，btc、usc, 默认btc

     返回JSON dictionary

     code - 0(成功), 其他(失败)

     id - 订单ID

     返回结果示例：

     {
     "code": 0,
     "msg": "Suceess",
     "result": true,
     "data": {
     "id": 28
     }
     }
     * @throws Exception
     */
    @Override
    public JSONObject trustCancel(String domain, String area, String coin, String id) throws TradeException {
        try {
            String httpUrl = domain + TRUST_CANCEL + area;
            String nonce = String.valueOf(new Date().getTime()).substring(0, 12);
            String signature = MD5Util.getMessageDigest(BTCTRADE_PRIVATE_KEY);
            String paramsValue = "key=" + BTCTRADE_PUBLIC_KEY + "&nonce=" + nonce + "&id=" + id + "&coin=" + coin;
            String parms = paramsValue + "&signature=" + MD5Util.sha256_HMAC(paramsValue, signature);
            //请求数据
            String result = HttpsUtils.net(httpUrl, parms, HttpsUtils.METHOD_POST);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if("Suceess".equals(jsonObject.getString("msg"))){
                JSONObject jsonData = jsonObject.getJSONObject("data");
                if(ObjectUtil.isNotEmpty(jsonData)){
                    System.out.println(jsonData);
                }
            }
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

    /**
     * 下单
     * Path：/api/v1/trust_add/region/{btc|usc}

     Request类型：POST

     参数

     key - API key

     signature - signature

     nonce - nonce

     amount - 购买数量

     price - 购买价格

     type - 买单或者卖单//"buy" or "sell"

     coin - coin

     region - 交易区：可选，btc、usc, 默认btc

     返回JSON dictionary

     id - 挂单ID

     code - 0(成功), 其他(失败)

     返回结果示例：

     {
     "code": 0,
     "msg": "Suceess",
     "result": true,
     "data": {
     "id": 28
     }
     }
     * @throws Exception
     */
    @Override
    public JSONObject trustAdd(String domain, String area, String coin, String amount, String price, String type) throws TradeException {
        try {
            String httpUrl = domain + TRUST_ADD + area;
            String nonce = String.valueOf(new Date().getTime()).substring(0, 12);
            String signature = MD5Util.getMessageDigest(BTCTRADE_PRIVATE_KEY);
            String paramsValue = "key=" + BTCTRADE_PUBLIC_KEY + "&nonce=" + nonce + "&amount=" + amount + "&price=" + price + "&type=" + type + "&coin=" + coin;
            String parms = paramsValue + "&signature=" + MD5Util.sha256_HMAC(paramsValue, signature);
            //请求数据
            String result = HttpsUtils.net(httpUrl, parms, HttpsUtils.METHOD_POST);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if("Suceess".equals(jsonObject.getString("msg"))){
                JSONObject jsonData = jsonObject.getJSONObject("data");
                if(ObjectUtil.isNotEmpty(jsonData)){
                    System.out.println(jsonData);
                }
            }
            return JSONObject.parseObject(result);
        } catch (Exception e){
            throw new TradeException(e);
        }
    }

}
